<template>
  <el-aside
    :width="isCollapsed ? '64px' : '200px'"
    style="background-color: #545c64; position: relative"
    overflow="hidden"
  >
    <el-button
      @click="toggleCollapse"
      style="
        position: absolute;
        top: 40%;
        right: -8px;
        transform: translateY(-50%);
        z-index: 1000;
      "
      circle
    >
      <el-icon>
        <ArrowRight v-if="isCollapsed" />
        <ArrowLeft v-else />
      </el-icon>
    </el-button>
    <el-menu
      v-if="menus && menus.length"
      :default-active="menus[0]?.path"
      class="el-menu-vertical-demo"
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b"
      :collapse="isCollapsed"
    >
      <template v-for="item in menus">
        <el-sub-menu
          v-if="item.children && item.children.length"
          :key="'submenu-' + item.id"
          :index="item.path"
          :popper-append-to-body="true"
          popper-class="menu-popper"
        >
          <template #title>
            <component
              :is="Icons[item.icon as keyof typeof Icons]"
              style="width: 20px; height: 20px; margin-right: 10px"
            />
            <span v-if="!isCollapsed">{{ item.name }}</span>
          </template>
          <el-menu-item
            v-for="subItem in item.children"
            :key="subItem.id"
            :index="subItem.path"
            @click="handleMenuClick(subItem.path)"
          >
            <component
              :is="Icons[subItem.icon as keyof typeof Icons]"
              style="width: 20px; height: 20px; margin-right: 10px"
            />
            {{ subItem.name }}
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item
          v-else
          :key="'menuitem-' + item.id"
          :index="item.path"
          @click="handleMenuClick(item.path)"
        >
          <component
            :is="Icons[item.icon as keyof typeof Icons]"
            style="width: 20px; height: 20px; margin-right: 10px"
          />
          <span v-if="!isCollapsed">{{ item.name }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </el-aside>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store/userStore";
import { ElIcon } from "element-plus";
import { ArrowLeft, ArrowRight } from "@element-plus/icons-vue";
import * as Icons from "@element-plus/icons-vue";
const router = useRouter();
const userStore = useUserStore();
const menus = ref(userStore.menuTree);
const isCollapsed = ref(false);

const handleMenuClick = (path: string) => {
  router.push(path);
};
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};
</script>

<style scoped>
.el-aside {
  transition: width 0.3s;
}
.el-menu-vertical-demo {
  border-right: none;
}
.collapse {
  color: white;
  margin-left: 20px;
}
.menu-popper {
  width: 50px !important;
}
</style>
